package com.tianlang.security.tool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import com.tianlang.domain.pojo.Authority;
import com.tianlang.security.tool.AcegiUtil;
import com.tianlang.service.IBaseManager;
import com.tianlang.service.IAuthorityManager;
import com.tianlang.util.ConfigReload;

@SuppressWarnings("rawtypes")
public class DefaultApplicationSetupListener implements ApplicationListener {

	@Autowired
	private IBaseManager baseManager;
	@Autowired
	private IAuthorityManager authorityManager;

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof ContextRefreshedEvent) {
			try {
				saveDefaultConfig();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 加载权限
	 * 
	 * @throws Exception
	 */
	private void saveDefaultConfig() throws Exception {
		ConfigReload cr = new ConfigReload();
		String devMode = cr.getProp().getProperty("devMode");
		// 全部删除 重新加载的开关
		if (devMode.equals("true")) {
			baseManager.delete("delete Authority");
			HashMap<String, List<Authority>> map = AcegiUtil.getDefaultConfig();
			List<Authority> list = AcegiUtil.Transform(map);
			for (Authority authority : list) {
				baseManager.saveObject(authority);
			}
		} else {
			Map<String, List<Authority>> db = authorityManager.loadAll();
			Map<String, List<Authority>> config = AcegiUtil.getDefaultConfig();
			for (String key : config.keySet()) {
				List<Authority> dbItem = db.get(key);
				if (dbItem == null) {
					List<Authority> configItem = config.get(key);
					for (Authority authority : configItem) {
						baseManager.saveObject(authority);
					}
				}
			}
		}

	}

}
